<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="/static/css/home.css">
</head>
<body>
  <h1>首页</h1>
  <button id="add">增加一个商品</button>
  <ul>
    <% for(var i=0;i<items.length;i++) { %>
      <li>
        <h2>商品名称：<%= items[i].itemName %></h2>
        <p>商品价格：<%= items[i].itemPrice %></p>
        <p>商品库存：<%= items[i].itemNum %></p>
        <button class="del" item_id="<%= items[i]._id %>">删除商品</button>
        <button class="update" item_id="<%= items[i]._id %>">更新商品</button>
      </li>
    <% } %>
  </ul>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <script>
    // 增加商品
    $("#add").click(function(){
      $.ajax({
        url: '/addItem',
        type: 'post',
        data: {
          itemName:"商品n",
          itemPrice: 11,
          itemNum: 2
        },
        success: function(res){
          if(res.code === 0) {
            alert('增加成功')
          }else{
            alert('增加失败')
          }
        }
      })
    })
    // 修改商品
    $('.update').click(function(){
      
      $.ajax({
        url: '/updateItem',
        type: 'post',
        data: {
          _id: $(this).attr('item_id'),
          itemPrice: 55.5
        },
        success: function(res){
          if(res.code === 0) {
            alert(res.msg)
          } else{
            alert(res.msg)
          }
        }
      })
    })
    // 删除商品
    $('.del').click(function(){
      
      $.ajax({
        url: '/delItem',
        type: 'post',
        data: {
          _id: $(this).attr('item_id'),
        },
        success: function(res){
          if(res.code === 0) {
            alert(res.msg)
          } else{
            alert(res.msg)
          }
        }
      })
    })
  </script>
</body>
</html>